package org.qiyu.live.im.core.server.handler.impl;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import jakarta.annotation.Resource;
import org.apache.rocketmq.client.producer.MQProducer;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.qiyu.live.common.interfaces.enums.ImCoreServerIPRedisKey;
import org.qiyu.live.im.core.server.common.ChannelHandlerContextCache;
import org.qiyu.live.im.core.server.common.ImContextUtils;
import org.qiyu.live.im.core.server.common.ImMsg;
import org.qiyu.live.im.core.server.common.ImMsgCodeEnum;
import org.qiyu.live.im.core.server.handler.SimpleHandler;
import org.qiyu.live.im.dto.ImMsgBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.qiyu.live.im.core.server.dto.ImOfflineDTO;

import static org.qiyu.live.common.interfaces.topic.ImCoreServerProviderTopicNames.IM_OFFLINE_TOPIC;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-10-07
 * Time: 16:47
 */
@Component
public class LogoutMsgHandler implements SimpleHandler {

    private final Logger LOGGER = LoggerFactory.getLogger(LoginMsgHandler.class);

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private MQProducer mqProducer;


    /**
     * 登出的handler实现
     * 1. 校验心跳包
     * 2. 回传msg
     * 3. 请传
     *
     * @param ctx
     * @param msg
     */
    @Override
    public void handler(ChannelHandlerContext ctx, ImMsg msg) {
        // 1. 校验
        Long userId = ImContextUtils.getUserId(ctx);
        Integer appId = ImContextUtils.getAppId(ctx);
        if (userId == null || appId == null) {
            LOGGER.error("userId or appId error msg={}", msg);
            ctx.close();
            throw new IllegalArgumentException("userId or appId error");
        }
        logoutSuccess(ctx, userId, appId);
        sendLoginMQ(userId, appId, null);
    }

    /**
     * 监听用户上线,发送消息给MQ
     *
     * @param userId 用户id
     * @param appId  产品id
     * @param roomId 直播间id
     */
    private void sendLoginMQ(Long userId, Integer appId, Integer roomId) {
        ImOfflineDTO imOfflineDTO = new ImOfflineDTO();
        imOfflineDTO.setRoomId(roomId);
        imOfflineDTO.setUserId(userId);
        imOfflineDTO.setAppId(appId);
        imOfflineDTO.setLoginTime(System.currentTimeMillis());
        Message message = new Message();
        message.setTopic(IM_OFFLINE_TOPIC);
        message.setBody(com.alibaba.fastjson.JSON.toJSONBytes(imOfflineDTO));
        try {
            SendResult sendResult = mqProducer.send(message);
            LOGGER.info("发送消息成功 res is {}", sendResult);
        } catch (Exception e) {
            LOGGER.error("[sendLoginMQ] 发送消息失败", e);
        }
    }

    private void logoutSuccess(ChannelHandlerContext ctx, Long userId, Integer appId) {
        // 2. 回传消息
        ImMsgBody msgBody = new ImMsgBody();
        msgBody.setAppId(appId);
        msgBody.setUserId(userId);
        msgBody.setData("true");
        ImMsg imMsg = ImMsg.build(ImMsgCodeEnum.IM_LOGOUT_MSG.getCode(), JSON.toJSONString(JSON.toJSONString(msgBody)));

        stringRedisTemplate.delete(ImCoreServerIPRedisKey.ImCoreServerIp + appId + ":" + userId);

        ctx.writeAndFlush(imMsg);
        // 3. 关闭连接
        ChannelHandlerContextCache.remove(userId);
    }
}